/*
 *  copyfile.h
 *  UnixSysPro
 *
 *  Created by ? ? on 07-8-20.
 *  Copyright 2007 __MyCompanyName__. All rights reserved.
 *
 */

#include <unistd.h>
#include <fcntl.h>

#define BUFSIZE		512
#define PERM		0644

// copy filename1 to filename2

int copyfile(const char *filename1, const char *filename2)
{
	int infile, outfile;
	ssize_t nread;
	char buffer[BUFSIZE];
	
	if((infile = open(filename1, O_RDONLY)) ==-1)
		return (-1);
	if((outfile = open(filename2,O_WRONLY|O_CREAT|O_TRUNC,PERM))== -1)
	{
		close (infile);
		return (-2);
	}
	
	// now read from filename1 BUFFSIZE chars at a time
	while((nread = read(infile,buffer,BUFSIZE))>0)
	{
		if(write(outfile,buffer,nread) < nread)
		{
			close(infile);
			close(outfile);
			return (-3);
		}
	}
			
	close(infile);
	close(outfile);
	
	if(nread == -1)
		return (-4);
	else
		return (0);
}

